package us.mooresr.webtroopmanager.client.activity;

import java.util.List;

import us.mooresr.webtroopmanager.client.ClientFactory;
import us.mooresr.webtroopmanager.client.TroopManagerService;
import us.mooresr.webtroopmanager.client.TroopManagerServiceAsync;
import us.mooresr.webtroopmanager.client.events.UserAddedEvent;
import us.mooresr.webtroopmanager.client.events.UserAddedHandler;
import us.mooresr.webtroopmanager.client.events.UserDeletedEvent;
import us.mooresr.webtroopmanager.client.events.UserDeletedHandler;
import us.mooresr.webtroopmanager.client.ui.UserListView;
import us.mooresr.webtroopmanager.shared.UserSummary;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AcceptsOneWidget;

public class UserListActivity extends MyActivity implements UserListView.Presenter {
	
	public UserListActivity(ClientFactory clientFactory) {
		super(clientFactory);
		
	}
	
	public void start(AcceptsOneWidget panel, EventBus eventBus) {
		super.start(panel, eventBus);
		
		UserListView userListView = clientFactory.getUserListView();
		userListView.setPresenter(this);
		panel.setWidget(userListView.asWidget());
		
		loadData();
		
		eventBus.addHandler(UserDeletedEvent.TYPE,new UserDeletedHandler() {
			
			@Override
			public void onDeleteUser(UserDeletedEvent event) {
				UserListView userListView = clientFactory.getUserListView();
				userListView.removeUser(event.getDeletedId());
			}
		});
		
		eventBus.addHandler(UserAddedEvent.TYPE, new UserAddedHandler() {

			@Override
			public void onAddUser(UserAddedEvent event) {
				UserListView userListView = clientFactory.getUserListView();
				userListView.addUser(event.getUser());
				
			}
			
		});
	}
	
	private void loadData() {
		TroopManagerServiceAsync troopManagerService = (TroopManagerServiceAsync) GWT.create(TroopManagerService.class);
		
		
		AsyncCallback<List<UserSummary>> callback = new AsyncCallback<List<UserSummary>>() {

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onSuccess(List<UserSummary> result) {
				
				clientFactory.getUserListView().setData(result);
				clientFactory.getUserListView().setStatus("Ready.");
			}
		};
		clientFactory.getUserListView().setStatus("Retrieving data...");
		troopManagerService.getAllUsers(callback);
	}

}
